<?php
/**
 * User: hjd-yao
 * Date: 2019/5/6
 * Time: 10:45
 */

namespace Develop\Models;

use App\Models\System\ChangeTypeModel as BaseChangeTypeModel;
use Illuminate\Http\Request;
use Overtrue\Pinyin\Pinyin;

class ChangeTypeModel extends BaseChangeTypeModel
{
    public function addType(Request $request)
    {
        $info = new self();
        $pinyin = new Pinyin();
        $data = $request->post();
        $name = arr2str($pinyin->convert($data['title']),'_');
        if(self::where('name',$name)->first()){
            $this->errorMsg = '改类型已存在';
            return false;
        }
        $info->name = $name;
        $info->title = $data['title'];
        $info->status = $request->post('status');
        $info->icon = $request->post('icon','hcl-default');
        $info->type = $request->post('type',0);
        return $info->save();
    }

    public function editType(Request $request,$id)
    {
        $info = self::find($id);
        if(!$info){
            $this->errorMsg = '编辑类型不存在';
            return false;
        }

        $is_update = false;
        $data = $request->post();

        if(isset($data['title'])&&
            $info->title !=$data['title']
        ){
            $pinyin = new Pinyin();
            $info->title = $data['title'];
            $info->name = arr2str($pinyin->convert($data['title']),'_');
            $is_update = true;
        }


        if(isset($data['icon'])&&$info->icon !=$data['icon']){
            $info->icon =$data['icon'];
            $is_update = true;
        }

        if(isset($data['type'])&&$info->icon !=$data['type']){
            $info->type =$data['type'];
            $is_update = true;
        }

        if(isset($data['status'])&&$info->status !=$data['status']){
            $info->icon =$data['status'];
            $is_update = true;
        }
        if($is_update){
            return $info->save();
        }
        return true;
    }
}